//
//  WeatherModel.m
//  GetFit3.0
//
//  Created by 圆圆陈 on 2017/12/25.
//  Copyright © 2017年 lxc. All rights reserved.
//

#import "WeatherModel.h"
#import <QuartzCore/QuartzCore.h>
@interface WeatherModel ()<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *localManager;
@property(nonatomic,strong)CLGeocoder *geocoder;
@property(nonatomic,strong)NSTimer *weatherTimer;
@end

@implementation WeatherModel
-(instancetype)init{
    self=[super init];
    if (self) {
        _weatherCode = [NSString string];
        _weatherInfo = [NSString string];
        _weatherName =@"getfit";
        _maxTem = @"0";
        _minTem = @"0";
        _tem = @"0";
        _localManager = [[CLLocationManager alloc]init];
        //设置代理
        _localManager.delegate = self;
        //设置定位的精度
        [_localManager setDesiredAccuracy:kCLLocationAccuracyBest];
        //位置信息更新最小距离
        _localManager.distanceFilter = 20;
         if ([UIDevice currentDevice].systemVersion.floatValue >= 9.0) {
             _localManager.allowsBackgroundLocationUpdates = YES;
         }
        if ([_localManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [_localManager requestAlwaysAuthorization];
        }
        self.geocoder = [[CLGeocoder alloc] init];
    }
    return self;
}
-(void)startUpdateLocation{
    [self.weatherTimer invalidate];
    self.weatherTimer = nil;
    [_localManager startUpdatingLocation];
    self.weatherTimer = [NSTimer timerWithTimeInterval:60 target:self selector:@selector(startLocation) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.weatherTimer forMode:NSRunLoopCommonModes];
    
}
-(void)startLocation{
//    NSLog(@"请求一次系统时间");
    NSDate *date = [NSDate date];
    NSInteger hour = date.hour;
    NSInteger min = date.minute;
    NSInteger second = date.second;
    //（00:00 整点开始 0600 1200 1800 0000 整点推天气到手环）
    if (hour%6==0) {
        if ((min==1&&second==0)|| (min==0 && second<=59)) {
             [_localManager startUpdatingLocation];
        }
    }
}
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:{
            NSLog(@"用户还未进行授权");
            LogWrite(@"天气定位", @"用户还未进行授权", nil);
            break;
        }
        case kCLAuthorizationStatusDenied:{
            // 判断当前设备是否支持定位和定位服务是否开启
            if([CLLocationManager locationServicesEnabled]){
                
                NSLog(@"用户不允许程序访问位置信息或者手动关闭了位置信息的访问，帮助跳转到设置界面");
                LogWrite(@"天气定位", @"用户不允许程序访问位置信息或者手动关闭了位置信息的访问", nil);
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    [[UIApplication sharedApplication] openURL: url];
                }
            }else{
                NSLog(@"定位服务关闭,弹出系统的提示框,点击设置可以跳转到定位服务界面进行定位服务的开启");
                LogWrite(@"天气定位", @"定位服务关闭", nil);
            }
            break;
        }
        case kCLAuthorizationStatusRestricted:{
            NSLog(@"受限制的");
            LogWrite(@"天气定位", @"受限制的", nil);
            break;
        }
        case kCLAuthorizationStatusAuthorizedAlways:{
            NSLog(@"授权允许在前台和后台均可使用定位服务");
           LogWrite(@"天气定位", @"授权允许在前台和后台均可使用定位服务", nil);
            break;
        }
        case kCLAuthorizationStatusAuthorizedWhenInUse:{
            NSLog(@"授权允许在前台可使用定位服务");
            LogWrite(@"天气定位", @"授权允许在前台可使用定位服务", nil);
            break;
        }
        default:
            break;
    }
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    // 设备的当前位置
    CLLocation *userLocation = [locations lastObject];
    [self.geocoder reverseGeocodeLocation:userLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *pl = [placemarks firstObject];
        
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        NSString *url = @"/support/weather";
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:[NSString stringWithFormat:@"%.3f",userLocation.coordinate.latitude] forKey:@"lat"];
        [dict setObject:[NSString stringWithFormat:@"%.3f",userLocation.coordinate.longitude] forKey:@"lon"];
        if (pl) {
            NSString *str = [NSString stringWithFormat:@"%@%@%@",pl.addressDictionary[@"Country"],pl.addressDictionary[@"State"],pl.addressDictionary[@"City"]];
            [dict setObject:str forKey:@"city"];
        }else{
            LogWrite(@"天气定位", nil, @"未定位到");
            return;
        }
        // 获取天气信息
        [manager POST:url parameters:dict success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject)
         {
             if (responseObject[@"ret"] && [responseObject[@"ret"] intValue]==0)
             {
                [_localManager stopUpdatingLocation];
                 KK_WeatherModel.weatherInfo =responseObject[@"data"][@"cond_txt"];
                 KK_WeatherModel.maxTem =responseObject[@"data"][@"tmp_max"];
                 KK_WeatherModel.minTem =responseObject[@"data"][@"tmp_min"];
                 KK_WeatherModel.weatherCode =responseObject[@"data"][@"cond_code"];
                 KK_WeatherModel.tem = responseObject[@"data"][@"tmp"];
                 [KK_WeatherModel updateToDB];
                 if (KK_BLEConnect.isConnected) {
                     [KK_BLESend sendTemperatureParamWithBlock:^(id object, KKBLEAcceptType type) {
                         
                     }];
                 }
                 LogWrite(@"天气请求", nil, @"成功");
             } else {
                LogWrite(@"天气请求", nil, (responseObject[@"message"]));
             }
             
         } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
             LogWrite(@"天气请求", nil, ([error localizedDescription]));
         }];
        
    }];
}
//定位失败的回调方法
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"无法获取当前位置 error : %@",error.localizedDescription);

}
+(WeatherModel *)getModelFromDB{
    WeatherModel *model = [WeatherModel searchSingleWithWhere:@"weatherName=getfit" orderBy:nil];
    if (model)
    {
        return model;
    }
    else
    {
        model = [[WeatherModel alloc] init];
        [model saveToDB];
        return model;
    }
}
// 表名
+ (NSString *)getTableName
{
    return @"WeatherModel";
}

// 主键
+ (NSString *)getPrimaryKey
{
    return @"weatherName";
}

// 表版本
+ (int)getTableVersion
{
    return 1;
}

+ (void)initialize
{
    [super initialize];
}
@end
